<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <!-- 搜索操作 -->
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
          <el-button
            class="collapse-btn"
            type="text"
            @click="toggleSearch"
            :icon="showSearch ? 'ArrowDownBold' : 'ArrowUpBold'"
          >
            {{ showSearch ? "收起" : "展开" }}
          </el-button>
        </div>
      </template>

      <!-- 表单 -->
      <el-form
        :model="queryParams"
        ref="distributionGradeRef"
        :inline="true"
        v-show="showSearch"
        label-width="100px"
      >
        <el-form-item label="等级名称" prop="gradeName">
          <el-input
            v-model="queryParams.gradeName"
            placeholder="请输入等级名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="等级权重" prop="gradeWeight">
          <el-input
            v-model="queryParams.gradeWeight"
            placeholder="请输入等级权重"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="自购佣金比例" prop="selfRatio">
        <el-input
          v-model="queryParams.selfRatio"
          placeholder="请输入自购佣金比例"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
        <!-- <el-form-item label="一级佣金比例" prop="firstRatio">
        <el-input
          v-model="queryParams.firstRatio"
          placeholder="请输入一级佣金比例"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
        <!-- <el-form-item label="二级佣金比例" prop="secondRatio">
        <el-input
          v-model="queryParams.secondRatio"
          placeholder="请输入二级佣金比例"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
        <!-- <el-form-item label="生效最低订单金额" prop="minOrderAmount">
        <el-input
          v-model="queryParams.minOrderAmount"
          placeholder="请输入生效最低订单金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
        <!-- <el-form-item label="是否默认等级" prop="isDefault">
        <el-select
          v-model="queryParams.isDefault"
          placeholder="请选择是否默认等级"
          clearable
        >
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in wdm_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="版本号" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入版本号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:distributionGrade:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:distributionGrade:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:distributionGrade:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:distributionGrade:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      border
      resizable
      :data="distributionGradeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        min-width="60"
        align="center"
        prop="gradeId"
      />
      <el-table-column
        label="等级名称"
        align="center"
        min-width="150"
        prop="gradeName"
      />
      <el-table-column label="等级" align="center" prop="gradeWeight" />
      <!-- <el-table-column label="自购佣金比例" align="center" prop="selfRatio" /> -->
      <!-- <el-table-column label="一级佣金比例" align="center" prop="firstRatio" /> -->
      <!-- <el-table-column label="二级佣金比例" align="center" prop="secondRatio" /> -->
      <!-- <el-table-column
        label="生效最低订单金额"
        align="center"
        prop="minOrderAmount"
      /> -->

      <!-- <el-table-column
        label="默认"
        align="center"
        prop="isDefault"
      >
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isDefault" />
        </template>
      </el-table-column> -->

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="版本号" align="center" prop="version" /> -->
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column
        label="操作"
        min-width="150"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:distributionGrade:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:distributionGrade:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分销等级对话框 -->
    <el-dialog :title="title" v-model="open" width="720px" append-to-body>
      <el-collapse v-model="activeCollapse">
        <!-- 基础信息组 -->
        <el-collapse-item name="basic" title="基础信息">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="等级名称" prop="gradeName">
                <el-input
                  v-model="form.gradeName"
                  placeholder="请输入等级名称(如:普通分销员)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="等级权重" prop="gradeWeight">
                <el-input
                  v-model="form.gradeWeight"
                  placeholder="请输入(越大等级越高)"
                  @input="validateWeight"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 佣金配置组 -->
        <el-collapse-item name="commission" title="佣金配置">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="自购佣金比例(%)" prop="selfRatio">
                <el-input
                  v-model="form.selfRatio"
                  placeholder="请输入(0-100)"
                  @input="validateRatio('selfRatio')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="一级佣金比例(%)" prop="firstRatio">
                <el-input
                  v-model="form.firstRatio"
                  placeholder="请输入(0-100)"
                  @input="validateRatio('firstRatio')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="二级佣金比例(%)" prop="secondRatio">
                <el-input
                  v-model="form.secondRatio"
                  placeholder="请输入(0-100)"
                  @input="validateRatio('secondRatio')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生效最低订单金额" prop="minOrderAmount">
                <el-input
                  v-model="form.minOrderAmount"
                  placeholder="请输入(元)"
                  @input="validateAmount('minOrderAmount')"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 等级属性组 -->
        <el-collapse-item name="attributes" title="等级属性">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否默认等级" prop="isDefault">
                <el-select
                  v-model="form.isDefault"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in sys_yes_no"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in wdm_status"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 系统信息组 -->
        <el-collapse-item name="system" title="系统信息">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="删除标志" prop="delFlag">
                <el-radio-group v-model="form.delFlag">
                  <el-radio
                    v-for="dict in del_flag"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本号" prop="version">
                <el-input
                  v-model="form.version"
                  disabled
                  placeholder="系统自动管理"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注信息" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  rows="3"
                  placeholder="请输入等级说明"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DistributionGrade">
import {
  listDistributionGrade,
  getDistributionGrade,
  delDistributionGrade,
  addDistributionGrade,
  updateDistributionGrade,
} from "@/api/ruoyi/distributionGrade";

// 在 onMounted 中设置默认展开的折叠面板
import { onMounted } from "vue";
onMounted(() => {
  activeCollapse.value = ["basic", "commission"];
});

const { proxy } = getCurrentInstance();
const { wdm_status, sys_yes_no, del_flag } = proxy.useDict(
  "wdm_status",
  "sys_yes_no",
  "del_flag"
);

const distributionGradeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    gradeName: null,
    gradeWeight: null,
    selfRatio: null,
    firstRatio: null,
    secondRatio: null,
    minOrderAmount: null,
    isDefault: null,
    status: null,
    version: null,
  },
  rules: {
    gradeName: [
      { required: true, message: "等级名称不能为空", trigger: "blur" },
      { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
    ],
    gradeWeight: [
      { required: true, message: "等级权重不能为空", trigger: "blur" },
      { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" },
      { validator: validateWeightRule, trigger: "blur" },
    ],
    selfRatio: [
      { required: true, message: "自购佣金比例不能为空", trigger: "blur" },
      { validator: validateRatioRule, trigger: "blur" },
    ],
    firstRatio: [
      { required: true, message: "一级佣金比例不能为空", trigger: "blur" },
      { validator: validateRatioRule, trigger: "blur" },
    ],
    secondRatio: [
      { required: true, message: "二级佣金比例不能为空", trigger: "blur" },
      { validator: validateRatioRule, trigger: "blur" },
    ],
    minOrderAmount: [
      { required: true, message: "生效最低订单金额不能为空", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "请输入有效金额",
        trigger: "blur",
      },
      { validator: validateMinOrderAmount, trigger: "blur" },
    ],
    isDefault: [
      { required: true, message: "请选择是否默认等级", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 添加响应式数据
const activeCollapse = ref(["basic", "commission", "attributes"]);

// 验证函数
// 验证等级权重
function validateWeight(value) {
  if (value && !/^\d+$/.test(value)) {
    form.value.gradeWeight = value.replace(/\D/g, "");
  }
}

// 验证等级权重
function validateWeightRule(rule, value, callback) {
  const weight = parseInt(value);
  if (weight < 1 || weight > 100) {
    callback(new Error("权重应在1-100范围内"));
  } else {
    callback();
  }
}

// 验证佣金比例
function validateRatio(field) {
  return (value) => {
    if (value && !/^\d*\.?\d{0,2}$/.test(value)) {
      form.value[field] = value.match(/^\d*\.?\d{0,2}/)[0];
    }
    if (parseFloat(value) > 100) {
      form.value[field] = "100";
    }
  };
}

// 验证佣金比例
function validateRatioRule(rule, value, callback) {
  const ratio = parseFloat(value);
  if (isNaN(ratio) || ratio < 0 || ratio > 100) {
    callback(new Error("比例应在0-100范围内"));
  } else {
    callback();
  }
}

// 验证金额
function validateAmount(field) {
  return (value) => {
    if (value && !/^\d*\.?\d{0,2}$/.test(value)) {
      form.value[field] = value.match(/^\d*\.?\d{0,2}/)[0];
    }
  };
}

// 验证金额
function validateMinOrderAmount(rule, value, callback) {
  const amount = parseFloat(value);
  if (isNaN(amount) || amount < 0) {
    callback(new Error("请输入有效金额"));
  } else {
    callback();
  }
}

// 新增：搜索区域折叠/展开
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

/** 查询分销等级列表 */
function getList() {
  loading.value = true;
  listDistributionGrade(queryParams.value).then((response) => {
    // distributionGradeList.value = response.rows
    distributionGradeList.value = response.rows.filter(
      (item) => item.delFlag !== "2"
    );
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

const distributionGradeRef = shallowRef();
// 表单重置
function reset() {
  form.value = {
    gradeId: null,
    gradeName: null,
    gradeWeight: null,
    selfRatio: null,
    firstRatio: null,
    secondRatio: null,
    minOrderAmount: null,
    isDefault: null,
    status: null,
    delFlag: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  // proxy.resetForm("distributionGradeRef");
  // 使用 nextTick 确保表单引用已存在
  nextTick(() => {
    if (distributionGradeRef.value) {
      distributionGradeRef.value.resetFields();
    }
  });
  activeCollapse.value = ["basic", "commission", "attributes", "system"];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.gradeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加分销等级";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _gradeId = row.gradeId || ids.value;
  getDistributionGrade(_gradeId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改分销等级";
  });
}

/** 提交按钮 */
function submitForm() {
  // 确保在 nextTick 中执行，等待 DOM 更新
  nextTick(() => {
    if (!distributionGradeRef.value) {
      proxy.$modal.msgError("表单尚未完全加载，请稍后再试");
      return;
    }

    distributionGradeRef.value.validate((valid) => {
      if (valid) {
        if (form.value.gradeId != null) {
          updateDistributionGrade(form.value)
            .then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            })
            .catch((error) => {
              console.error("修改失败:", error);
              proxy.$modal.msgError(
                "修改失败: " + (error.message || "未知错误")
              );
            });
        } else {
          addDistributionGrade(form.value)
            .then((response) => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            })
            .catch((error) => {
              console.error("新增失败:", error);
              proxy.$modal.msgError(
                "新增失败: " + (error.message || "未知错误")
              );
            });
        }
      } else {
        proxy.$modal.msgError("表单验证失败，请检查输入");
      }
    });
  });
}
// function submitForm() {
//   proxy.$refs["distributionGradeRef"].validate((valid) => {
//     if (valid) {
//       if (form.value.gradeId != null) {
//         updateDistributionGrade(form.value).then((response) => {
//           proxy.$modal.msgSuccess("修改成功");
//           open.value = false;
//           getList();
//         });
//       } else {
//         addDistributionGrade(form.value).then((response) => {
//           proxy.$modal.msgSuccess("新增成功");
//           open.value = false;
//           getList();
//         });
//       }
//     }
//   });
// }

/** 删除按钮操作 */
function handleDelete(row) {
  const _gradeIds = row.gradeId || ids.value;
  proxy.$modal
    .confirm('是否确认删除分销等级编号为"' + _gradeIds + '"的数据项？')
    .then(function () {
      return delDistributionGrade(_gradeIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/distributionGrade/export",
    {
      ...queryParams.value,
    },
    `distributionGrade_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
/* 搜索卡片样式 */
.search-card {
  /* margin-bottom: 16px; */
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.collapse-btn {
  padding: 0;
  font-size: 14px;
  color: #606266;
}
</style>
